import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { RouteRecordRaw } from 'vue-router'
import { login, getUserInfo } from '@/api/login'
import { transToTree, generateMenuRoutes } from '@/utils'

const useUserStore = defineStore('user', () => {
  const token = ref<string>('') // token
  const userInfo = ref<IUserInfo>() // 用户基本信息
  const role = ref<IRole>() // 用户角色

  const menuRoutes = ref<RouteRecordRaw[]>([]) // 菜单路由表

  /**
   * 登录的 action 方法
   * @param arg 
   */
  const loginAction = async (arg: ILoginAccount) => {
    const {status, message, token: responseToken} = await login(arg)
    // console.log('登录结果:', {status, message, token})
    
    if (status === 200) { // 登录成功
      token.value = responseToken as string
      return {
        success: true,
      }
    }

    // 登录失败
    token.value = ''
    return {
      success: false,
      message
    }
  }

  /**
   * 获取登录用户的基本信息
   */
  const getUserInfoAction = async() => {
    const result = await getUserInfo()
    console.log('用户基本信息:', result.userInfo)
    if (result.status === 200) {
      userInfo.value = result.userInfo
      role.value = result.roles[0]

      // 生成菜单路由表
      genMenuRoutes()
    } else {
      userInfo.value = undefined
      role.value = undefined
    }
  }

  /**
   * 根据角色权限生成菜单路由表
   */
  const genMenuRoutes = () => {
    if (!role.value?.permissions) {
      return
    }
    // 获取角色权限中的菜单
    const menuPermissions = (<IPermission[]>role.value.permissions).filter(item => item.type === 1)

    console.log('menuPermissions:', menuPermissions)
    
    const _menuRoutes = generateMenuRoutes(transToTree(menuPermissions))

    console.log('_menuRoutes:', _menuRoutes)
    menuRoutes.value = _menuRoutes
  }

  return {
    token,
    userInfo,
    role,
    menuRoutes,
    loginAction,
    getUserInfoAction,
  }
}, {
  persist: {
    storage: sessionStorage,
    pick: ['token']
  }
})

export default useUserStore